package cyan.gf.core;

import cyan.gf.control.MessageBox;
import cyan.gf.util.PropReader;
import cyan.gf.util.StagePool;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.io.*;

/**
 * Created by cyan on 2017/2/15.
 * Email:qsyan@vip.qq.com
 */
public class Initializer extends Application {

  public static int DEF_WIDTH = 1050;
  public static int DEF_HEIGHT = 700;


  @Override
  public void start(Stage primaryStage) throws Exception {
    PropReader.load("/cyan/gf/properties/config.properties");
    Parent root = FXMLLoader.load(getClass().getResource("/cyan/gf/fxml/initializer.fxml"));
    Scene primaryScene = new Scene(root, DEF_WIDTH, DEF_HEIGHT);
    primaryStage.setTitle(String.format("%s (%s)", PropReader.getString("app.title"), PropReader.getString("app.version")));
    primaryStage.setScene(primaryScene);
    primaryStage.getIcons().addAll(new Image("/cyan/gf/resource/images/logo.png"));
    primaryStage.show();
    StagePool.put("main", primaryStage);
    initTemplete();
  }

  public void initTemplete() {
    PropReader.load("/cyan/gf/properties/config.properties");
    String templeteDir = System.getProperty("user.home") + "\\.GeneratorFx\\templete\\";
    String[] templetes = PropReader.getString("app.templetes").split(",");
    String tempExt = ".ftl";
    File propDir = new File(templeteDir);
    File tempFile;
    if (!propDir.exists()) {
      if (!propDir.mkdirs()) {
        MessageBox.showResult(StagePool.get("main"), Alert.AlertType.ERROR, "error", "Templete file load error.");
      }
    }
    for (String tempName : templetes) {
      tempFile = new File(templeteDir + tempName + tempExt);
      if (!tempFile.exists()) {
        copyTempete("/cyan/gf/resource/templete/" + tempName + tempExt, templeteDir + tempName + tempExt);
      }
    }
  }

  public void copyTempete(String resourceDir, String destDir) {
    InputStream in = null;
    FileOutputStream out = null;
    try {
      int byteread;
      in = getClass().getResourceAsStream(resourceDir);
      File destFile = new File(destDir);
      out = new FileOutputStream(destFile);
      byte[] buffer = new byte[1024];
      while ((byteread = in.read(buffer)) != -1) {
        out.write(buffer, 0, byteread);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        assert in != null;
        in.close();
        assert out != null;
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    launch(args);
  }

}
